package com.vitabuybuy.tv.ui.home.coupons.viewmodel

import androidx.databinding.ObservableArrayList
import com.library.common.base.BaseViewModel
import com.library.common.base.MessageModel
import com.library.common.ext.rxHttpRequest
import com.library.common.net.error.msg
import com.library.common.net.loadingtype.LoadingType
import com.library.common.toast.XToast
import com.vitabuybuy.tv.BR
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.dto.CouponCenterDto
import com.vitabuybuy.tv.inter.OnCouponCenterClickListener
import com.vitabuybuy.tv.network.CouponCenterRepository
import me.tatarka.bindingcollectionadapter2.ItemBinding
import me.tatarka.bindingcollectionadapter2.OnItemBind

class CouponsCenterViewModel : BaseViewModel() {

    private val itemOnClickListener = object : OnCouponCenterClickListener {
        override fun onItemClick(item: CouponCenterDto, position: Int) {
            defUI.msgEvent.postValue(MessageModel(2, arg1 = position, obj = item))
        }
    }

    val couponList = ObservableArrayList<CouponCenterDto>()
    val couponBinding: OnItemBind<CouponCenterDto> =
        OnItemBind { itemBinding: ItemBinding<Any>, position: Int, item: CouponCenterDto ->
            itemBinding.set(BR.itemBean, R.layout.item_coupons_1).bindExtra(BR.position, position)
                .bindExtra(BR.listenner, itemOnClickListener)
        }

    fun getCouponList(pageNumber: Int, categoryId: Int) {
        val map = HashMap<String, Any?>()
        if (categoryId != -1) map["category"] = mapOf(Pair("id", categoryId))
        rxHttpRequest {
            onRequest = {
                val it = CouponCenterRepository.getCouponsList(map, pageNumber).await()
                if (pageNumber == 1) {
                    couponList.clear()
                }
                couponList.addAll(it)
                if (couponList.isEmpty()) {
                    statusView.set(LoadingType.SHOW_EMPTY)
                }else{
                    statusView.set(LoadingType.SHOW_CONTENT)
                }
                defUI.msgEvent.postValue(MessageModel(1, arg1 = it.size))
            }
            onError = {
                XToast.normal(it.msg)
            }
            isLoadingType = true
            isRefresh = pageNumber == 1
        }
    }

    fun saveACoupon(couponId: Int, position: Int) {
        rxHttpRequest {
            onRequest = {
                CouponCenterRepository.saveACoupon(couponId).await()
                defUI.msgEvent.postValue(MessageModel(3, arg1 = position))
            }
            onError = {
                XToast.normal(it.msg)
            }
            isShowDialogRequest = true
        }
    }
}
